package com.yuda.afterexamscore.controller;

import cn.hutool.json.JSONUtil;
import com.mysql.cj.x.protobuf.MysqlxCrud;
import com.yuda.afterexamscore.domain.ThDimensionQuestion;
import com.yuda.afterexamscore.domain.ThQuesTypeAnalysis;
import com.yuda.afterexamscore.service.ISpartaSubjectService;
import com.yuda.afterexamscore.service.IThQuesTypeAnalysisService;
import com.yuda.afterexamscore.utils.SequentialUuidHexGenerator;
import com.yuda.common.core.annotation.Excel;
import com.yuda.common.core.utils.IdUtils;
import com.yuda.common.core.utils.poi.ExcelUtil;
import com.yuda.common.core.web.controller.BaseController;
import com.yuda.common.core.web.domain.AjaxResult;
import com.yuda.common.core.web.page.TableDataInfo;
import com.yuda.common.log.annotation.Log;
import com.yuda.common.log.enums.BusinessType;
import com.yuda.common.security.annotation.PreAuthorize;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.omg.PortableServer.THREAD_POLICY_ID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;

/**
 * 题目分析题号Controller
 *
 * @author wyn
 * @date 2021-05-12
 */
@RestController
@RequestMapping("/thQuesTypeAnalysis")
public class ThQuesTypeAnalysisController extends BaseController
{
    @Autowired
    private IThQuesTypeAnalysisService thQuesTypeAnalysisService;
    @Autowired
    private ISpartaSubjectService iSpartaSubjectService;

    /**
     * 查询题目分析题号列表
     */
//    @PreAuthorize(hasPermi = "afterexamscore:analysis:list")
    @GetMapping("/list")
    public TableDataInfo list(ThQuesTypeAnalysis thQuesTypeAnalysis)
    {
        startPage();
        List<ThQuesTypeAnalysis> list = thQuesTypeAnalysisService.selectThQuesTypeAnalysisList(thQuesTypeAnalysis);
        return getDataTable(list);
    }

    /**
     * 导出题目分析题号列表
     */
//    @PreAuthorize(hasPermi = "afterexamscore:analysis:export")
    @Log(title = "题目分析题号", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ThQuesTypeAnalysis thQuesTypeAnalysis) throws IOException
    {
        List<ThQuesTypeAnalysis> list = thQuesTypeAnalysisService.selectThQuesTypeAnalysisList(thQuesTypeAnalysis);
        for (ThQuesTypeAnalysis sis:list
             ) {
            String arr = iSpartaSubjectService.selectSpartaSubjectByRelationSubjectId(sis.getSubjectArr());
            sis.setSubjectArr(arr);
        }
        ExcelUtil<ThQuesTypeAnalysis> util = new ExcelUtil<ThQuesTypeAnalysis>(ThQuesTypeAnalysis.class);
        util.exportExcel(response, list, "analysis");
    }

    @PostMapping("/exportExcelModel")
    public void exportExcelModel(HttpServletResponse response) throws IOException {
        //获取系统的环境
        String env = System.getProperty("os.name").toLowerCase();
        String path = "C:\\Users\\61974\\Desktop\\";
        if (env.contains("linux")) {
            path = "/mnt/excelModel/ThQuesTypeAnalysis/";
        }
        String fileName = "QTA_model.xlsx";

        File file = new File(path+fileName);

        ServletOutputStream outputStream = response.getOutputStream();
        byte[] bytes = FileCopyUtils.copyToByteArray(file);
        response.setHeader("Content-Disposition", "attachment; filename=题型分析.xlsx");
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();
    }
   /* @PreAuthorize(hasPermi = "afterexamscore:analysis:import")
    @Log(title = "题目分析题号", businessType = BusinessType.IMPORT)*/
    @PostMapping("/import")
    public AjaxResult importTest( MultipartFile multipartFile,ThQuesTypeAnalysis thQuesTypeAnalysis) throws Exception {
        InputStream inputStream =  multipartFile.getInputStream();
        ExcelUtil<ThQuesTypeAnalysis> excelUtil = new ExcelUtil<>(ThQuesTypeAnalysis.class);
        //获取文件的名字
        if(multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".") + 1).equals("xlsx")) {
            Workbook wb = WorkbookFactory.create(inputStream);
            Sheet sheet = wb.getSheetAt(0);
            String sheetName = sheet.getSheetName();
            wb.close();
            InputStream input = multipartFile.getInputStream();
            //新插入的数据
            List<ThQuesTypeAnalysis> listNew = excelUtil.importExcel(sheetName, input);
            //新插入的数据最后一个参数 进入数据库查询 重新set 之后便于比较 //该部分还需要改善
            for (ThQuesTypeAnalysis sis : listNew
            ) {
                sis.getSubjectArr().trim();
                sis.getSubjectName().trim();
                sis.getQuesTypeName().trim();
                sis.getQuesIndex().trim();
                if (sis.getSubjectName() == null || sis.getSubjectName() == "" || sis.getQuesTypeName() == null || sis.getQuesTypeName() == "" || sis.getQuesIndex() == null || sis.getQuesIndex() == "" || sis.getSubjectArr() == null || sis.getSubjectArr() == "" || (sis.getFullScore() == null)) {
                    return AjaxResult.error("表内数据不正确");
                } else {
                    String[] sub_Arry = sis.getSubjectArr().split(":");
                    if (sub_Arry.length > 1) {
                        sis.setSubjectArr(iSpartaSubjectService.selectSpartaSubjectIdbyName(sub_Arry[1], sub_Arry[0]).toString());
                    } else {
                        return AjaxResult.error("表内数据不正确");
                    }
                }

            }
            //表里原来有的数据
            List<ThQuesTypeAnalysis> listOld = thQuesTypeAnalysisService.selectThQuesTypeAnalysisList(thQuesTypeAnalysis);
            //求交集
//        List<ThQuesTypeAnalysis> intersection =listNew.stream().filter(item ->
//                listOld.stream().map(ThQuesTypeAnalysis::changetoString).collect(Collectors.toList()).contains(item.changetoString())
//        ).collect(Collectors.toList());
            //求差集
            List<ThQuesTypeAnalysis> different = listNew.stream().filter(item -> !
                    listOld.stream().map(ThQuesTypeAnalysis::changetoString).collect(Collectors.toList()).contains(item.changetoString())
            ).collect(Collectors.toList());
            if (different.size() != 0) {
                for (ThQuesTypeAnalysis th : different) {
                    th.setUuid(SequentialUuidHexGenerator.generate());
                }
                thQuesTypeAnalysisService.insertThQuesTypeAnalysisExcel(different);
            } else {
                return AjaxResult.success("插入的数据已存在于数据库中");
            }
            //List<ThQuesTypeAnalysis> collect = listNew.stream().filter(x -> listOld.contains(x)).collect(toList());
        }else{
            return AjaxResult.error("上传文件不是excel格式");
        }
        inputStream.close();
        return AjaxResult.success("操作成功");

    }
    /**
     * 获取题目分析题号详细信息
     */
//    @PreAuthorize(hasPermi = "afterexamscore:analysis:query")
    @GetMapping(value = "/{uuid}")
    public AjaxResult getInfo(@PathVariable("uuid") String uuid)
    {
        return AjaxResult.success(thQuesTypeAnalysisService.selectThQuesTypeAnalysisById(uuid));
    }

    /**
     * 新增题目分析题号对应显示名称
     */
//    @PreAuthorize(hasPermi = "afterexamscore:analysis:add")
    @Log(title = "题目分析题号", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ThQuesTypeAnalysis thQuesTypeAnalysis)
    {   //接收传过来的对象
        String str0 = thQuesTypeAnalysis.getSubjectArr();
        //获取对象的subjectArr值(string)
        System.out.println(str0);
        //对该对象的值进行分割存到String类型的数组
        String[] subjectidStrings = str0.split(",");
        //获取科目id个数准备转换为int类型
        int length = subjectidStrings.length;
        Long[] subjectidsints = new  Long[length];
        //将String类型转换成int类型
        for(int i =0 ;i<length;i++){
            subjectidsints[i]=Long.parseLong(subjectidStrings[i]);
            Class c = subjectidsints[i].getClass();
        }
        //设置一个string类型的变量将科目名称拼接
        String Subjectname = " ";
        for(int i=0;i<length;i++){
            subjectidStrings[i]=null;
        }
        //建立一个SQL语句从spart_subject表中查出对应的Name
        for(int i= 0;i<length;i++){
            subjectidStrings[i] = iSpartaSubjectService.selectSubjectNameById(subjectidsints[i]);
            Subjectname = Subjectname +" "+subjectidStrings[i];
        }
        //拼接完成 最后进行设置
        thQuesTypeAnalysis.setSubjectName(Subjectname);
        thQuesTypeAnalysis.setUuid(IdUtils.fastSimpleUUID());
        return toAjax(thQuesTypeAnalysisService.insertThQuesTypeAnalysis(thQuesTypeAnalysis));
    }

    /**
     * 修改题目分析题号
     */
//    @PreAuthorize(hasPermi = "afterexamscore:analysis:edit")
    @Log(title = "题目分析题号", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ThQuesTypeAnalysis thQuesTypeAnalysis)
    {
        //接收传过来的对象
        String str0 = thQuesTypeAnalysis.getSubjectArr();
        //获取对象的subjectArr值（string)
        System.out.println(str0);
        //对该对象的值进行分割 存到 String 类型的数组
        String[] subjectidStrings = str0.split(",");
        //获取科目id个数 准备转换为int类型
        int length = subjectidStrings.length;
        Long[] subjectidsints = new  Long[length];
        //将String类型 转换成 int 类型
        for(int i =0 ;i<length;i++){
            subjectidsints[i]=Long.parseLong(subjectidStrings[i]);
            Class c = subjectidsints[i].getClass();
        }
        //设置一个string类型的变量将科目名称拼接
        String Subjectname = " ";
        for(int i=0;i<length;i++){
            subjectidStrings[i]=null;
        }
        //建立一个SQL语句从spart_subject表中查出对应的Name
        for(int i= 0;i<length;i++){
            subjectidStrings[i] = iSpartaSubjectService.selectSubjectNameById(subjectidsints[i]);
            Subjectname = Subjectname+" "+subjectidStrings[i];
        }
        //拼接完成 最后进行设置
        thQuesTypeAnalysis.setSubjectName(Subjectname);
        return toAjax(thQuesTypeAnalysisService.updateThQuesTypeAnalysis(thQuesTypeAnalysis));
    }

    /**
     * 删除题目分析题号
     */
//    @PreAuthorize(hasPermi = "afterexamscore:analysis:remove")
    @Log(title = "题目分析题号", businessType = BusinessType.DELETE)
	@DeleteMapping("/{uuids}")
    public AjaxResult remove(@PathVariable String[] uuids)
    {
        return toAjax(thQuesTypeAnalysisService.deleteThQuesTypeAnalysisByIds(uuids));
    }
    @GetMapping("/truncateTable")
    public void RemoveAll(){
         thQuesTypeAnalysisService.truncateTable();
//         System.out.println("操作成功");
    }
}
